<template>
  <section class="number">
    <el-input v-model.number="value" type="text" :disabled="disabled" :placeholder="placeholder" :min="min" :max="max" :clearable="clearable" @input="handleInput" @change="handleChange">
      <template v-if="slot" slot="append">{{ slot }}</template>
    </el-input>
  </section>
</template>
<script>
import mixins from './../mixins'
import { isNumeric } from '@/utils'
export default {
  name: 'VNumber',
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default: {}
    }
  },
  computed: {
    slot () {
      return this.option.slot || ''
    },
    clearable () {
      return this.option.clearable
    }
  },
  methods: {
    getValue () {
      return +this.value
    },

    setValue (k) {
      if (isNumeric(k)) {
        this.$set(this, 'value', k)
      }
      this.setCheck()
    },

    setCheck () {
      let { value, required, max, min } = this
      let error = false, errorMsg = ''
      if (value !== undefined && value !== null) {
        value = value + ''
      }
      if (required && !value) {
        error = true
        errorMsg = '必填选项不能为空'
      }
      if (!error) {
        value = +value
        min = +min
        max = +max
        if (required || value) {
          if (!error) {
            if (value) {
              if (value > max) {
                error = true
                errorMsg = `超过最大值${max}`
              } else if (value < min) {
                error = true
                errorMsg = `小于最小值${min}`
              } else {
                error = false
              }
            }
          }
        }
      }
      this.error_ = error
      this.error_message_ = errorMsg
      this.fieldCheck()
    },

    handleInput (e) {
      if (isNumeric(e)) {
        this.dispatch_event('filed-value-change', e)
      }
    },

    handleChange (e) {
      this.setCheck()
      if (!isNumeric(e)) {
        this.value = this.opton.value
      }
    }
  }
}
</script>
